<template>
    <Page>
        <el-form ref="form" :model="form">
            <Panel title="店铺信息">
                <el-form ref="myForm" :model="form" :rules="formRules">
                    <el-form-item label="父类分级" prop="pid_level">
                        <el-cascader
                            size="small"
                            v-model="form.pid_level"
                            :options="listData"
                            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
                            placeholder="请选择"
                            clearable
                            style="width: 100%"
                        />
                    </el-form-item>
                    <el-form-item label="标题" prop="name">
                        <el-input v-model="form.name" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="控制器名" prop="controller_name">
                        <el-input v-model="form.controller_name" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="方法名" prop="action_name">
                        <el-input  v-model="form.action_name" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="图标" prop="code"> 
                        <el-input  v-model="form.code" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
                        <el-input type="number" v-model="form.sort" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="路由地址" prop="url">
                        <el-input  v-model="form.url" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="导航状态" prop="state">
                        <el-radio-group v-model="form.state">
                            <el-radio :label="true">显示</el-radio>
                            <el-radio :label="false">隐藏</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </Panel>
            <Panel title="">
                <el-form-item>
                    <el-button type="primary" size="small" @click="onSubmit('form')">提交</el-button>
                </el-form-item>
            </Panel>
        </el-form>
    </Page>
</template>

<script>
import Page from "@/components/page/Page";
import Panel from "@/components/panel/Panel";

export default {
    data() {
        return {
            form: {
                pid_level: '',    // 店铺地址
                name: '',      // 店铺电话
                controller_name: '',      // 营业时间
                action_name: '',      // 经营商品
                code: '',      // 经营商品
                url: '',      // 经营商品
                sort: '',      // 经营商品
                state: null,      // 初始值设置为 null，与 el-radio-group 类型匹配
            },
            formRules: {
                // pid_level: [
                //     { required: true, message: '请输入请输入父类分级', trigger: 'blur' }
                // ],
                name: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
                ],
                controller_name: [
                    { required: true, message: '请输入控制器名', trigger: 'blur' }
                ],
                action_name: [
                    { required: true, message: '请输入方法名', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入图标', trigger: 'blur' }
                ],
                url: [
                    { required: true, message: '请输入路由地址', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                ],
                state: [
                    { required: true, message: '请选择状态', trigger: 'change' } // 建议使用 change 触发，因为是单选框
                ]
            },
            mchTypeList: { 12: '企业', 11: '个体工商户' },
            agree: false,
            areaCode: [],
            areaList: [],
            showButtonText:{},
            listData:[],
            pidlevel:""
        }
    },
    created() {},
    mounted() {
        this.initData();
        // this.getAreaTree();
    },
    methods: {
        initData() {
            // this.$http.get('/admin/AuthNode/lists', { params: this.params }).then(result => {
                    this.$http.get('/admin/AuthNode/listsNew ', {params: this.params }).then(result => {
                if (result.code === 200) {
                    // 直接赋值为树结构
                    this.listData = Object.values(result.data);
                    // 初始化 showButtonText
                    this.listData.forEach(item => {
                        this.showButtonText[item.id] = false;
                    });
                    // 修复：如果有pid参数，递归查找路径并赋值
                    if (this.$route.query.pid) {
                        const pid = Number(this.$route.query.pid);
                        const path = this.findPathById(this.listData, pid);
                        if (path.length) {
                            this.form.pid_level = path;
                        }
                    }
                    console.log(this.listData);
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        // 递归查找id链路
        findPathById(tree, id, path = []) {
            for (let node of tree) {
                const newPath = path.concat(node.id);
                if (node.id === id) {
                    return newPath;
                }
                if (node.children && node.children.length) {
                    const res = this.findPathById(node.children, id, newPath);
                    if (res.length) return res;
                }
            }
            return [];
        },
        handleSelectChange() {
            if (!this.form.pid_level) {
                this.pidlevel = '0_0';
                return;
            }
            const selectedValue = this.form.pid_level;
            const selectedItem = this.listData.find(item => item.name === selectedValue);
            this.pidlevel = selectedItem.id + "_" + selectedItem.level;
        },
        // 提交数据
        onSubmit(form) {
            // 修改为验证内层的 el-form
            this.$refs['myForm'].validate((valid) => {
                if (valid) {
                    // 递归查找父节点的 id 和 level，拼接成 'id_level'
                    if (Array.isArray(this.form.pid_level)) {
                        const lastId = this.form.pid_level[this.form.pid_level.length - 1];
                        const node = this.findNodeById(this.listData, lastId);
                        if (node) {
                            this.form.pid_level = `${node.id}_${node.level}`;
                            // this.form.pid_level = '6_2';
                        } else {
                            this.form.pid_level = '';
                        }
                    }
                    this.$http.post('/admin/AuthNode/edit', this.form).then(result => {
                        if (result.code == 200) {
                            this.$message.success(result.msg);
                            this.$router.back();
                        } else {
                            this.$message.error(result.msg);
                        }
                    });
                }
            });
        },
        // 递归查找节点
        findNodeById(tree, id) {
            for (let node of tree) {
                if (node.id === id) return node;
                if (node.children && node.children.length) {
                    const res = this.findNodeById(node.children, id);
                    if (res) return res;
                }
            }
            return null;
        },

    },
    components: {
        Page,
        Panel
    }
}
</script>

<style lang="less" scoped>
::v-deep(.el-upload){
    .el-upload-dragger{
        height:120px;
        width:180px;
    }
}
</style>
